import React, { useRef, useState, useEffect } from 'react'
import { Button, List } from 'antd'
//import listenDirectory from '../../util/ListenDirectory'
import watch from 'watch'
import {  getCurrentTime } from '../../util/helper'

function ListenGuard() {

    const [listenDic, setListenDic] = useState("")
    const [dicWatcher, setDicWatcher] = useState(null)
    const [changeRecord, setChangeRecord] = useState([])

    useEffect(() => {
        console.log(dicWatcher)

        if (dicWatcher) {
          dicWatcher.on('created', (f, stat) => {
            let record = '创建文件: ' + f + " 于 " + getCurrentTime()
            setChangeRecord((prev) => [...prev, record])
          })

          dicWatcher.on('changed', (f, stat) => {
            let record = '修改文件: ' + f + " 于 " + getCurrentTime()
            setChangeRecord((prev) => [...prev, record])
            console.log(changeRecord)
          })

          dicWatcher.on('removed', (f, stat) => {
            let record = '删除文件: ' + f + " 于 " + getCurrentTime()
            setChangeRecord((prev) => [...prev, record])
            console.log(changeRecord)
          })
        }


        return () => {
          if (dicWatcher) {
            try {
              dicWatcher.stop()
            } catch {
            } finally {
              setChangeRecord([])
            }
          }
        }
    }, [dicWatcher])

    const fileInput = useRef(null)

    const callFileDialog = () => {
        fileInput.current.click()
    }

    const fileChange = (files) => {
        if (files.length === 0) {
          return
        }
        let file = files[0].path
        if (file) {
          let parent = file.split('\\')
          parent.pop() // 父目录
          setListenDic(parent.join('\\'))
          watch.createMonitor(parent.join('\\'), (monitor) => {
            setDicWatcher(monitor)
          })
        }
    }

    return (
        <div>
            <header>
                <div style={{padding:"14px"}}>
                    <Button type="primary" size='large' style={{float:"right"}}
                        onClick={() => {callFileDialog()}}
                    >
                    添加监听
                    </Button>
                    <input type="file" style={{ display: "none"}}
                        ref={fileInput} onChange={() => {fileChange(fileInput.current.files)}}
                    />
                </div>
            </header>
            <div style={{padding:"25px", textAlign:"center"}}>
                <h2>{listenDic === "" ? "未监听任何目录" : "正在监听: " + listenDic}</h2>
                <List
                  size="large"
                  dataSource={changeRecord}
                  bordered
                  renderItem={
                    item => <List.Item>{item}</List.Item>
                  }
                 />
            </div>
        </div>
    )
}

export default ListenGuard
